﻿namespace KeppelLand.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Remoting.Metadata.W3cXsd2001;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;
    using System.Xml;
    using System.Configuration;
    using System.Data.SqlClient;

    /// <summary>
    /// Summary description for EmailHelper
    /// </summary>
    public class EmailHelper
    {
        public EmailHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static void SendExceptionAlertEmail(string body)
        {
            string SmtpServer = System.Configuration.ConfigurationManager.AppSettings["Smtp_Server"];
            string SenderEmail = System.Configuration.ConfigurationManager.AppSettings["Sender_Email"];
            string SenderName = System.Configuration.ConfigurationManager.AppSettings["Sender_Name"];
            string EmailQueuePath = System.Configuration.ConfigurationManager.AppSettings["Email_Queue_Path"];
            string DeveloperEmail = System.Configuration.ConfigurationManager.AppSettings["Developer_Email"];
            string DeveloperName = System.Configuration.ConfigurationManager.AppSettings["Developer_Name"];

            // TODO: Refactor the hard-coded bits to be read from configuration settings instead.
            System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(SmtpServer);
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
            mailMessage.From = new System.Net.Mail.MailAddress(SenderEmail, SenderName);
            mailMessage.To.Add(new System.Net.Mail.MailAddress(DeveloperEmail, DeveloperName));
            mailMessage.Subject = "An exception has occurred on e-Overtime claims.";
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.Body = body;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            mailMessage.IsBodyHtml = false;
            smtpClient.Send(mailMessage);

            //SendEmail(DeveloperEmail, "test", body, false);
        }

        public static void SendStartEndAlertEmail(string body)
        {
            string SmtpServer = System.Configuration.ConfigurationManager.AppSettings["Smtp_Server"];
            string SenderEmail = System.Configuration.ConfigurationManager.AppSettings["Sender_Email"];
            string SenderName = System.Configuration.ConfigurationManager.AppSettings["Sender_Name"];
            string EmailQueuePath = System.Configuration.ConfigurationManager.AppSettings["Email_Queue_Path"];
            string DeveloperEmail = System.Configuration.ConfigurationManager.AppSettings["Developer_Email"];
            string DeveloperName = System.Configuration.ConfigurationManager.AppSettings["Developer_Name"];

            // TODO: Refactor the hard-coded bits to be read from configuration settings instead.
            //System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(SmtpServer);
            //System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
            //mailMessage.From = new System.Net.Mail.MailAddress(SenderEmail, SenderName);
            //mailMessage.To.Add(new System.Net.Mail.MailAddress(DeveloperEmail, DeveloperName));
            //mailMessage.Subject = "An application start/end has occurred on Staff-Overtime claims.";
            //mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            //mailMessage.Body = body;
            //mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            //mailMessage.IsBodyHtml = false;
            //smtpClient.Send(mailMessage);

            SendEmail(DeveloperEmail, body, body, false);
        }

        public static void SendEmail(string emailAddress, string emailSubject, string emailBody, bool isBodyHtml)
        {
            string SmtpServer = System.Configuration.ConfigurationManager.AppSettings["Smtp_Server"];
            string SenderEmail = System.Configuration.ConfigurationManager.AppSettings["Sender_Email"];
            string SenderName = System.Configuration.ConfigurationManager.AppSettings["Sender_Name"];
            string EmailQueuePath = System.Configuration.ConfigurationManager.AppSettings["Email_Queue_Path"];
            string DeveloperEmail = System.Configuration.ConfigurationManager.AppSettings["Developer_Email"];
            string DeveloperName = System.Configuration.ConfigurationManager.AppSettings["Developer_Name"];

            const string Email_CharSet = "UTF-8";

            ASPEMAILLib.IMailSender mailMessage = new ASPEMAILLib.MailSender();
            mailMessage = new ASPEMAILLib.MailSender();
            mailMessage.Host = SmtpServer;
            mailMessage.From = SenderEmail;
            mailMessage.FromName = mailMessage.EncodeHeader(SenderName, Email_CharSet);

            mailMessage.CharSet = Email_CharSet;
            mailMessage.ContentTransferEncoding = "Quoted-Printable";
            mailMessage.Subject = mailMessage.EncodeHeader(emailSubject, Email_CharSet);

            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase)))
            {
                mailMessage.AddAddress(ConfigurationManager.AppSettings["Simulate_Email"].Trim(), "Email-simulation");
                emailBody = emailBody + "<p>Simulate email; Intended recipient is: " + emailAddress;
            }
            else
            {
                mailMessage.AddAddress(emailAddress);
            }

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AlwaysBcc"].Trim()))
            {
                mailMessage.AddBcc(ConfigurationManager.AppSettings["AlwaysBcc"].Trim());
            }

            mailMessage.Body = emailBody;
            mailMessage.IsHTML = isBodyHtml? 1 : 0;
            //mailMessage.Queue = 0;
            //mailMessage.Send();
            mailMessage.Queue = 1;
            mailMessage.Send(EmailQueuePath);

            LogEmailSent(emailAddress, emailSubject, emailBody, isBodyHtml);
        }

        public static void LogEmailSent(string emailAddress, string emailSubject, string emailBody, bool isBodyHtml)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
            {
                System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = "INSERT INTO [SentEmail] (emailAddress, emailSubject, emailBody, isBodyHtml) VALUES (@emailAddress, @emailSubject, @emailBody, @isBodyHtml);";
                
                cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
                cmd.Parameters.AddWithValue("@emailSubject", emailSubject);
                cmd.Parameters.AddWithValue("@emailBody", emailBody);
                cmd.Parameters.AddWithValue("@isBodyHtml", isBodyHtml);
                
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
    }

    public class CryptographyHelper
    {
        public CryptographyHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static byte[] HexStringToBytes(string hexString)
        {
            byte[] result = null;

            try
            {
                SoapHexBinary hexBin = SoapHexBinary.Parse(hexString);
                result = hexBin.Value;
                return result;
            }
            catch
            {
                return result;
            }
        }

        public static string BytesToHexString(byte[] bytes)
        {
            string result = string.Empty;

            try
            {
                SoapHexBinary hexBin = new SoapHexBinary(bytes);
                result = hexBin.ToString();
                return result;
            }
            catch
            {
                return result;
            }
            
        }

        public static string Encrypt(string plainText)
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
            desCrypto.Key = Convert.FromBase64String(System.Configuration.ConfigurationManager.AppSettings["Cryptography_Key"]);
            desCrypto.IV = Convert.FromBase64String(System.Configuration.ConfigurationManager.AppSettings["Cryptography_IV"]);
            System.IO.MemoryStream ms = null;
            using (ms = new MemoryStream())
            using (CryptoStream cs = new CryptoStream(ms, desCrypto.CreateEncryptor(), CryptoStreamMode.Write))
            using (StreamWriter sw = new StreamWriter(cs))
            {
                sw.AutoFlush = true;
                sw.Write(plainText);
            }

            return BytesToHexString(ms.ToArray());
        }

        public static string Decrypt(string hexCipherText)
        {
            string result = string.Empty;
            byte[] cipherBytes = HexStringToBytes(hexCipherText);

            if (cipherBytes != null)
            {
                DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
                desCrypto.Key = Convert.FromBase64String(System.Configuration.ConfigurationManager.AppSettings["Cryptography_Key"]);
                desCrypto.IV = Convert.FromBase64String(System.Configuration.ConfigurationManager.AppSettings["Cryptography_IV"]);
                System.IO.MemoryStream ms = null;
                using (ms = new MemoryStream(cipherBytes))
                using (CryptoStream cs = new CryptoStream(ms, desCrypto.CreateDecryptor(), CryptoStreamMode.Read))
                using (StreamReader sr = new StreamReader(cs))
                {
                    result = sr.ReadToEnd();
                }
            }

            return result;
        }
    }

    public class TranslationHelper
    {
        public TranslationHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static string GetUsernameByDomainName(string domainName)
        {
            string intranetId = string.Empty;

            //Original code that takes domain into account for domainName uniqueness
            //string domain = "KEPPELLAND";
            //if (domainName.StartsWith(domain, StringComparison.InvariantCultureIgnoreCase))
            //{
            //    intranetId = domainName.Remove(0, domain.Length).Replace("\\", string.Empty);
            //}

            int separatorIndex = domainName.IndexOf("\\");
            if (separatorIndex == -1)
            {
                intranetId = domainName;
            }
            else
            {
                intranetId = domainName.Remove(0, separatorIndex + 1);
            }

            return intranetId;
        }

        public static string GetEmployeeMaster(string intranetId)
        {
            string result = string.Empty;

            string cacheEntryName = "EmployeeMasterDictionary";

            Dictionary<string, string> emDict = HttpContext.Current.Cache.Get(cacheEntryName) as Dictionary<string, string>;
            if (emDict == null)
            {
                emDict = new Dictionary<string, string>();
            }

            if (emDict.Keys.Contains(intranetId))
            {
                result = emDict[intranetId];
            }
            else
            {
                // get from DB
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
                {
                    System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = "SELECT TOP 1 EmployeeMaster FROM B2E WHERE IntranetID = @IntranetID;";
                    cmd.Parameters.AddWithValue("@IntranetID", intranetId);

                    conn.Open();
                    using (System.Data.SqlClient.SqlDataReader sdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                    {
                        if (sdr.Read())
                        {
                            result = sdr[0].ToString();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(result))
                {
                    emDict[intranetId] = result;
                }
            }

            HttpContext.Current.Cache.Insert(cacheEntryName, emDict);

            return result;
        }

        public static string GetSectionByEmployeeMaster(string employeeMaster)
        {
            string result = string.Empty;

            string cacheEntryName = "EmployeeMaster_Section_Dictionary";

            Dictionary<string, string> em_nl = HttpContext.Current.Cache.Get(cacheEntryName) as Dictionary<string, string>;
            if (em_nl == null)
            {
                em_nl = new Dictionary<string, string>();
            }

            if (em_nl.Keys.Contains(employeeMaster))
            {
                result = em_nl[employeeMaster];
            }
            else
            {
                // get from DB
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
                {
                    System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = "SELECT TOP 1 Section FROM B2E WHERE EmployeeMaster = @EmployeeMaster;";
                    cmd.Parameters.AddWithValue("@EmployeeMaster", employeeMaster);

                    conn.Open();
                    using (System.Data.SqlClient.SqlDataReader sdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                    {
                        if (sdr.Read())
                        {
                            result = sdr[0].ToString();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(result))
                {
                    em_nl[employeeMaster] = result;
                }
            }

            HttpContext.Current.Cache.Insert(cacheEntryName, em_nl);

            return result;
        }

        public static string GetNameLegalByEmployeeMaster(string employeeMaster)
        {
            string result = string.Empty;

            string cacheEntryName = "EmployeeMaster_NameLegal_Dictionary";

            Dictionary<string, string> em_nl = HttpContext.Current.Cache.Get(cacheEntryName) as Dictionary<string, string>;
            if (em_nl == null)
            {
                em_nl = new Dictionary<string, string>();
            }

            if (em_nl.Keys.Contains(employeeMaster))
            {
                result = em_nl[employeeMaster];
            }
            else
            {
                // get from DB
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
                {
                    System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
                    cmd.CommandText = "SELECT TOP 1 NameLegal FROM B2E WHERE EmployeeMaster = @EmployeeMaster;";
                    cmd.Parameters.AddWithValue("@EmployeeMaster", employeeMaster);

                    conn.Open();
                    using (System.Data.SqlClient.SqlDataReader sdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                    {
                        if (sdr.Read())
                        {
                            result = sdr[0].ToString();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(result))
                {
                    em_nl[employeeMaster] = result;
                }
            }

            HttpContext.Current.Cache.Insert(cacheEntryName, em_nl);

            return result;
        }

        public static string GetNameLegalByDomainName(string domainName)
        {
            return GetNameLegalByEmployeeMaster(GetEmployeeMasterByDomainName(domainName));
        }

        public static string GetEmployeeMasterByDomainName(string domainName)
        {
            return GetEmployeeMaster(GetUsernameByDomainName(domainName));
        }

        public static string GetCheckboxFormValue(string formValue)
        {
            if (formValue != null)
                return true.ToString();
            else
                return string.Empty;
        }

        public static decimal? ParseDecimal(string formValue)
        {
            decimal decimalResult;

            if (decimal.TryParse(formValue, out decimalResult))
                return decimalResult;
            else
                return null;
        }

        public static bool? ParseBoolean(string formValue)
        {
            bool boolResult;

            if (bool.TryParse(formValue, out boolResult))
                return boolResult;
            else
                return null;
        }

        public static string ResolveUrl(string s)
        {
            return string.Empty;
        }

        public static string GetMonthName(string monthNum)
        {
            switch (monthNum)
            {
                case "1":
                    return "January";
                case "2":
                    return "February";
                case "3":
                    return "March";

                case "4":
                    return "April";
                case "5":
                    return "May";
                case "6":
                    return "June";

                case "7":
                    return "July";
                case "8":
                    return "August";
                case "9":
                    return "September";

                case "10":
                    return "October";
                case "11":
                    return "November";
                case "12":
                    return "December";

                default:
                    return string.Empty;
            }
        }

        public static string GetContentType(string format)
        {
            switch (format.ToUpperInvariant())
            {
                case "PDF":
                    return "application/pdf";
                case "EXCEL":
                    return "application/vnd.ms-excel";
                case "WORD":
                    return "application/msword";
                case "IMAGE":
                    return "image/tiff";
                default:
                    return "application/octet-stream";
            }
        }

        public static string GetFileName(string format, string filename)
        {
            switch (format.ToUpperInvariant())
            {
                case "PDF":
                    return string.Format("{0}.pdf", filename);
                case "EXCEL":
                    return string.Format("{0}.xls", filename);
                case "WORD":
                    return string.Format("{0}.doc", filename);
                case "IMAGE":
                    return string.Format("{0}.tiff", filename);
                default:
                    return string.Format("{0}", filename);
                    
            }
        }

        public static string GetClaimStatus(byte? status)
        {
            if (status.HasValue)
            {
                switch (status.Value)
                {
                    case (byte)KeppelLand.Entities.ClaimStatus.DRAFT:
                        return "Pending Submission";
                    case (byte)KeppelLand.Entities.ClaimStatus.SUBMITTED_TO_RO:
                        return "Pending 1st Approver";
                    case (byte)KeppelLand.Entities.ClaimStatus.SUBMITTED_TO_AO:
                        return "Pending 2nd Approver";
                    case (byte)KeppelLand.Entities.ClaimStatus.SUBMITTED_TO_HR:
                    case (byte)KeppelLand.Entities.ClaimStatus.CLEARED_BY_HR:
                    case (byte)KeppelLand.Entities.ClaimStatus.EXPORT_TO_SAP:
                        return "Processed(HR)";
                }
            }

            return "Unknown";
        }

        public static string ConvertToFilter(ref string frm_filter_entries)
        {
            string sql_filter = string.Empty;
            string[] entries = frm_filter_entries.Split(',');

            if (entries.Length > 0)
            {
                frm_filter_entries = "[";
                foreach (string en in entries)
                {
                    frm_filter_entries = frm_filter_entries + "'" + en + "',";

                    if (!string.IsNullOrEmpty(en.Trim()))
                    {
                        sql_filter = sql_filter + string.Format("{0},", en.Trim());
                    }
                }
                frm_filter_entries = frm_filter_entries.Remove(frm_filter_entries.Length - 1, 1);
                frm_filter_entries = frm_filter_entries + "]";
                if (sql_filter.Length > 0)
                {
                    sql_filter = sql_filter.Remove(sql_filter.Length - 1, 1);
                }
            }

            return sql_filter;
        }
    }

    public class FormatHelper
    {
        public static string FormatDate(object dateObject)
        {
            string result = string.Empty;

            if ((dateObject != null) && (dateObject.GetType() == typeof(System.DateTime)))
            {
                result = ((DateTime)dateObject).ToString("dd/MM/yyyy");
            }

            return result;
        }

        public static string FormatTime(object timeObject)
        {
            string result = string.Empty;
            
            if ((timeObject != null) && (timeObject.GetType() == typeof(System.DateTime)))
            {
                result = ((DateTime)timeObject).ToString("HHmm");
            }

            return result;
        }

        public static string FormatDayOfWeek(object dateObject)
        {
            string result = string.Empty;

            if ((dateObject != null) && (dateObject.GetType() == typeof(System.DateTime)))
            {
                result = ((DateTime)dateObject).ToString("ddd");
            }

            return result;
        }

        public static string FormatDecimal(object decimalObject)
        {
            string result = string.Empty;

            if ((decimalObject != null) && (decimalObject.GetType() == typeof(System.Decimal)))
            {
                result = ((Decimal)decimalObject).ToString("0.##");
            }

            return result;
        }

        public static string FormatMoney(object decimalObject)
        {
            string result = string.Empty;

            if ((decimalObject != null) && (decimalObject.GetType() == typeof(System.Decimal)))
            {
                result = ((Decimal)decimalObject).ToString("0.00");
            }

            return result;
        }

        public static string FormatCheckmark(object booleanObject)
        {
            string result = string.Empty;

            if ((booleanObject != null) && (booleanObject.GetType() == typeof(System.Boolean) && (((Boolean)booleanObject) == true)))
            {
                result = "V";
                //<text><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></text>
            }

            return result;
        }

    }

    /*
     *     <add key="Simulate_Supervisor" value="S1234434A"/>
    <add key="Simulate_Secretary" value="S7818584H"/>
    <add key="Simulate_Claimant" value="S7833007D"/>
    <add key="Simulate_HR" value="S1717328F"/>

     * */
    public enum Simul
    {
        CLAIMANT = 0,
        SUPERVISOR = 1, 
        HR = 2,
        SECRETARY = 3
    }

    public class UserIdentityHelper
    {
        public static string GetClaimantName()
        {
            string claimantName = System.Web.HttpContext.Current.User.Identity.Name;

            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Claimant"].Trim())))
            {
                claimantName = ConfigurationManager.AppSettings["Simulate_Claimant"].Trim();
            }

            return claimantName;
        }

        public static string GetSupervisorName()
        {
            string supervisorName = System.Web.HttpContext.Current.User.Identity.Name;

            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Claimant"].Trim())))
            {
                supervisorName = ConfigurationManager.AppSettings["Simulate_Claimant"].Trim();
            }

            if ((ConfigurationManager.AppSettings["Training_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Training_Supervisor"].Trim())))
            {
                supervisorName = ConfigurationManager.AppSettings["Training_Supervisor"].Trim();
            }

            return supervisorName;
        }

        public static bool IsSimulatingSupervisor()
        {
            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Supervisor"].Trim())))
                return true;
            else
                return false;
        }

        public static string GetHRName()
        {
            string claimantName = System.Web.HttpContext.Current.User.Identity.Name;

            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Claimant"].Trim())))
            {
                claimantName = ConfigurationManager.AppSettings["Simulate_Claimant"].Trim();
            }

            if ((ConfigurationManager.AppSettings["Training_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Training_HR"].Trim())))
            {
                claimantName = ConfigurationManager.AppSettings["Training_HR"].Trim();
            }

            return claimantName;
        }

        public static bool IsSimulatingHR()
        {
            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_HR"].Trim())))
                return true;
            else
                return false;
        }

        public static string GetSecretaryName()
        {
            string claimantName = System.Web.HttpContext.Current.User.Identity.Name;

            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Claimant"].Trim())))
            {
                claimantName = ConfigurationManager.AppSettings["Simulate_Claimant"].Trim();
            }

            //if ((ConfigurationManager.AppSettings["Training_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
            //    && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Training_Secretary"].Trim())))
            //{
            //    claimantName = ConfigurationManager.AppSettings["Training_Secretary"].Trim();
            //}

            return claimantName;
        }

        public static bool IsSimulatingSecretary()
        {
            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Secretary"].Trim())))
                return true;
            else
                return false;
        }

        public static bool IsSimulatingInputDate()
        {
            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Date"].Trim())))
                return true;
            else
                return false;
        }

        public static string GetInputDate()
        {
            if ((ConfigurationManager.AppSettings["Simulate_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Simulate_Date"].Trim())))
                return ConfigurationManager.AppSettings["Simulate_Date"];
            else
                return DateTime.Now.ToString("yyyy-MM-dd");
        }

        public static bool IsTraining()
        {
            if (ConfigurationManager.AppSettings["Training_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                return true;
            else
                return false;
        }

        public static string GetTrainingSupervisorName()
        {
            string supervisor = string.Empty;

            if ((ConfigurationManager.AppSettings["Training_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Training_Supervisor"].Trim())))
            {
                supervisor = ConfigurationManager.AppSettings["Training_Supervisor"].Trim();
            }

            return supervisor;
        }

        public static bool IsHRUser()
        {
            bool isHRUser = false;

            string claimantName = GetClaimantName();

            if ((ConfigurationManager.AppSettings["Training_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
                && (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Training_HR"].Trim())))
            {
                claimantName = ConfigurationManager.AppSettings["Training_HR"].Trim();
            }

            isHRUser = KeppelLand.Controllers.B2EController.IsHR(claimantName);

            return isHRUser;
        }

        public static bool IsTrainer()
        {
            bool isTrainer = false;

            string claimantName = GetClaimantName();

            char[] delimiters = new char[] { ',' };

            string[] trainers = ConfigurationManager.AppSettings["Trainer_CSV"].Trim().Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

            if (ConfigurationManager.AppSettings["Training_Mode"].Trim().Equals("On", StringComparison.InvariantCultureIgnoreCase))
            {
                if (trainers.Contains(claimantName, System.StringComparer.InvariantCultureIgnoreCase))
                    isTrainer = true;
            }
            else
            {
                isTrainer = true;
            }

            return isTrainer;
        }

    } // public class UserIdentityHelper

    //public struct SheetInfo
    //{
    //    public string SheetName;
    //    public string SheetType;

    //    public SheetInfo(string SheetName, string SheetType)
    //    {
    //        this.SheetName = SheetName;
    //        this.SheetType = SheetType;
    //    }
    //}

    //public class ExcelHelper
    //{
    //    public static List<SheetInfo> GetSheets(string filePath)
    //    {
    //        //  Return a generic list containing info about all the sheets.
    //        const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";

    //        //  Fill this collection with a list of all the sheets
    //        List<SheetInfo> sheets = new List<SheetInfo>();

    //        using (Package xlPackage = Package.Open(filePath, FileMode.Open, FileAccess.Read))
    //        {
    //            //  Get the main document part (workbook.xml).
    //            foreach (System.IO.Packaging.PackageRelationship relationship in xlPackage.GetRelationshipsByType(documentRelationshipType))
    //            {
    //                //  There should only be one document part in the package. 
    //                Uri documentUri = PackUriHelper.ResolvePartUri(
    //                    new Uri("/", UriKind.Relative), relationship.TargetUri);

    //                PackagePart documentPart = xlPackage.GetPart(documentUri);


    //                //  Load the contents of the workbook, which is all you need to retrieve the names and types of the sheets:
    //                XmlDocument doc = new XmlDocument();
    //                doc.Load(documentPart.GetStream());

    //                //  Create a NamespaceManager to handle the default namespace, and create a prefix for the default namespace:
    //                XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
    //                nsManager.AddNamespace("default", doc.DocumentElement.NamespaceURI);


    //                //  Loop through all the nodes, retrieving the information about each sheet:
    //                foreach (System.Xml.XmlNode node in doc.SelectNodes("//default:sheets/default:sheet", nsManager))
    //                {
    //                    string sheetName = string.Empty;
    //                    string sheetType = "worksheet";

    //                    sheetName = node.Attributes["name"].Value;
    //                    XmlAttribute typeAttr = node.Attributes["type"];

    //                    if (typeAttr != null)
    //                    {
    //                        sheetType = typeAttr.Value;
    //                    }

    //                    sheets.Add(new SheetInfo(sheetName, sheetType));
    //                }

    //                //  There's only one document part.
    //                break;
    //            }
    //        }
            
    //        return sheets;
    //    } // public static List<SheetInfo> GetSheets(string filePath)

    //}
} // namespace KeppelLand.Helpers